package com.bears.god.sup.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bears.god.sup.model.User;
import com.bears.god.sup.service.ServiceDAOFactory;
import com.bears.god.sup.service.UserService;

@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {

	/**
	 * ��¼�û�
	 */
	private static final long serialVersionUID = 000002L;

	private static final String METHOD_TOLOGIN = "0";
	private static final String METHOD_LOGIN = "1";

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);

	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("method");
		if (method != null) {
			switch (method) {
			case LoginServlet.METHOD_TOLOGIN:
				request.getRequestDispatcher("WEB-INF/view/user/login.jsp").forward(request, response);
				break;

			case LoginServlet.METHOD_LOGIN:
				Login(request, response);
				break;

			default:
				break;
			}
		}

	}

	private void Login(HttpServletRequest request, HttpServletResponse response) {
		UserService userservice = ServiceDAOFactory.getUserDAO();

		User user;

		try {
			user = userservice.findByName(request.getParameter("name"));
			if (user == null || !user.getPassword().equals(request.getParameter("password"))) {
				request.setAttribute("login_err", "用户密码错误");
				request.getRequestDispatcher("WEB-INF/view/user/login.jsp").forward(request, response);
				return;
			}

			request.getSession().setAttribute("s_user", user);
			if (user.getUserDept().equals("0")) {
				request.getSession().setAttribute("s_user", user);
				request.getRequestDispatcher("/Income").forward(request, response);
			} else if (user.getUserDept().equals("1")) {
				request.getSession().setAttribute("s_user", user);
				request.getRequestDispatcher("/Vendor").forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
